import React from 'react';
import { Route } from 'react-router';

import { checkLogin } from './actions/loginAction';

import DefaultPage from './containers/home/index';
import Category from './containers/home/category';
import Article from './containers/home/article';
import My from './containers/home/my';
import Login from './containers/auth/login';
import Signup from './containers/auth/signup';
import Admin from './containers/admin/index';
import Carousel from './containers/admin/carousel';
import Hot from './containers/admin/hot';
import Protocol from './containers/admin/protocol';
import AdminCategory from './containers/admin/category';
import AdminArticle from './containers/admin/article';
import ArticleEdit from './containers/admin/articleEdit';
import Member from './containers/admin/member';

/**
 * 判断用户是否登录
 * @param nextState
 * @param replace
 * @param callback
 * @returns {Promise.<void>}
 */
const checkCustomer = async (nextState, replace, callback) => {
  // 判断是否已经登录
  const isLogin = await checkLogin(1);
  if (!isLogin) {
    replace(`/login?type=1`);
    callback();
  }
  callback();
};

/**
 * 判断管理员是否登录
 * @param nextState
 * @param replace
 * @param callback
 * @returns {Promise.<void>}
 */
const checkAdmin = async (nextState, replace, callback) => {
  // 判断是否已经登录
  const isLogin = await checkLogin(0);
  if (!isLogin) {
    replace(`/login?type=0`);
    callback();
  }
  callback();
};

const routes = (
  <Route>
    <Route path="/" component={DefaultPage}></Route>
    <Route path="category" getComponent={async (location, cb) => {
      const { cid } = location.location.query;

      // 判断是否已经登录
      const isLogin = await checkLogin(1);

      if (+cid === 18 || +cid === 19) {
        if (isLogin) {
          cb(null, My);
        } else {
          cb(null, Login);
        }
        return;
      } else if (+cid === 20) {
        cb(null, Signup);
        return;
      }
      cb(null, Category);
    }}>
    </Route>
    <Route path="article" component={Article}></Route>
    <Route path="my" component={My} onEnter={checkCustomer}></Route>
    <Route path="login" component={Login}></Route>
    <Route path="admin" component={Admin} onEnter={checkAdmin}></Route>
    <Route path="admin/carousel" component={Carousel} onEnter={checkAdmin}></Route>
    <Route path="admin/hot" component={Hot} onEnter={checkAdmin}></Route>
    <Route path="admin/protocol" component={Protocol} onEnter={checkAdmin}></Route>
    <Route path="admin/category" component={AdminCategory} onEnter={checkAdmin}></Route>
    <Route path="admin/article" component={AdminArticle} onEnter={checkAdmin}></Route>
    <Route path="admin/article/edit" component={ArticleEdit} onEnter={checkAdmin}></Route>
    <Route path="admin/member" component={Member} onEnter={checkAdmin}></Route>
    {/*<Auth path="/admin" component={Admin}></Auth>*/}
  </Route>
);

export default routes;
